package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lu piaoyang
 * @Date 2020/9/16 15:30
 * @Version 1.0
 */
@Slf4j
@Component
@Service
public class ICartServiceImpl implements ICartService {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    CartConverter cartConverter;
    @Value("${redis-name.cart}")
    private String cart;
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
//        try {
        request.requestCheck();

        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        Long userId = request.getUserId();
        List<CartProductDto> list = (List<CartProductDto>) cart.get(userId);
        if (list==null){
            list = new ArrayList<>();
        }
        response.setCartProductDtos(list);
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
//        } catch (Exception e) {
//            log.error("ICartServiceImpl.addToCart == " + e);
//            ExceptionProcessorUtils.wrapperHandlerException(response, e);
//        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
//        try {
        request.requestCheck();
        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        Long userId = request.getUserId();
        List<CartProductDto> list = (List<CartProductDto>) cart.get(userId);
        if (list == null) {
            list = new ArrayList<>();
        }
        List<Long> itemIds = new ArrayList<>();
        for (CartProductDto cartProductDto : list) {
            itemIds.add(cartProductDto.getProductId());
        }

        Long itemId = request.getItemId();
        if (itemIds.contains(itemId)) {
            for (CartProductDto cartProductDto : list) {
                //修改已包含的商品数量
                if (cartProductDto.getProductId().equals(request.getItemId())) {
                    cartProductDto.setProductNum(cartProductDto.getProductNum() + request.getNum());
                }
            }
        }
        //不包含的商品则添加
        else {
            Item item = itemMapper.selectByPrimaryKey(itemId);
            CartProductDto cartProductDto = cartConverter.item2Dto(item);
            cartProductDto.setProductNum(request.getNum());
            cartProductDto.setChecked("true");
            list.add(cartProductDto);
        }
        cart.put(userId, list);

        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
//        } catch (Exception e) {
//            log.error("ICartServiceImpl.addToCart == " + e);
//            ExceptionProcessorUtils.wrapperHandlerException(response, e);
//        }
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();

        request.requestCheck();
        Long userId = request.getUserId();
        Long itemId = request.getItemId();
        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        List<CartProductDto> list = (List<CartProductDto>) cart.get(userId);
        for (CartProductDto cartProductDto : list) {
            //修改
            if (cartProductDto.getProductId().equals(itemId)) {
                cartProductDto.setChecked(request.getChecked());
                cartProductDto.setProductNum(request.getNum());
                break;
            }
        }
        cart.put(userId, list);

        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        Long userId = request.getUserId();
        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        List<CartProductDto> list = (List<CartProductDto>) cart.get(userId);
        for (CartProductDto cartProductDto : list) {
            //修改
            cartProductDto.setChecked(request.getChecked());
        }
        cart.put(userId, list);
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();

        request.requestCheck();
        Long userId = request.getUserId();
        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        List<CartProductDto> list = (List<CartProductDto>) cart.get(userId);
        for (CartProductDto cartProductDto : list) {
            //修改
            if (cartProductDto.getProductId().equals(request.getItemId())) {
                list.remove(cartProductDto);
                break;
            }
        }
        cart.put(userId, list);

        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();


        request.requestCheck();
        Long userId = request.getUserId();
        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        List<CartProductDto> oldList = (List<CartProductDto>) cart.get(userId);
        List<CartProductDto> newList = new ArrayList<>();
        for (CartProductDto cartProductDto : oldList) {
            if (cartProductDto.getChecked().equals("false")){
                newList.add(cartProductDto);
            }
        }
        cart.put(userId,newList);

        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        Long userId = request.getUserId();
        List<Long> productIds = request.getProductIds();
        RMap<Object, Object> cart = redissonClient.getMap(this.cart);
        List<CartProductDto> list = (List<CartProductDto>) cart.get(userId);
        List<CartProductDto> removeList = new ArrayList<>();
        for (Long productId : productIds) {
            for (CartProductDto cartProductDto : list) {
                if (cartProductDto.getProductId().equals(productId)){
                    removeList.add(cartProductDto);
                }
            }
        }
        list.removeAll(removeList);
        cart.put(userId, list);
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

}
